<template>
  <div>
    <!--搜索栏-->
    <el-form label-width="68px" :inline="true">
      <el-form-item label="链接名称" prop="name" style="float: left">
        <el-input v-model="query.name" placeholder="请输入链接名称" clearable size="small"/>
      </el-form-item>
      <el-form-item label="链接分类" prop="type" style="float: left">
        <el-select v-model="query.type" placeholder="请选择链接分类" clearable size="small">
          <el-option v-for="item in typeList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item style="float: left">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleInsert">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table v-loading="loading" :data="linkList" @selection-change="handleSelectionChange" :fit="true">
      <el-table-column type="selection" fixed align="center" width="55" />
      <el-table-column prop="id" v-if="false" label="ID" width="120" />
      <el-table-column prop="name" fixed align="center" label="链接名称" />
      <el-table-column prop="icon" align="center" label="链接图标"  >
        <template slot-scope="scope">
          <img width="100" height="100" :src="scope.row.icon"/>
        </template>
      </el-table-column>
      <el-table-column prop="url" align="center" label="链接地址" />
      <el-table-column prop="type" align="center" label="链接分类">
        <template slot-scope="scope">
          <span v-for="item in typeList" v-if="scope.row.type == item.value">{{item.name}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination style="margin-top: 20px"
      @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="query.pageNum" :page-sizes="[5,10,20,40]"
      :page-size="query.pageSize" layout="total, sizes, prev, pager, next"
      :total="total">
    </el-pagination>
    <!--添加/修改对话框-->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="linkForm" :rules="linkRules" label-width="120px" style="height:250px">
        <div style="float: left; width: 50%" >
          <el-form-item label="链接名称" prop="name">
            <el-input v-model="linkForm.name" placeholder="请输入链接名称" />
          </el-form-item>
          <el-form-item label="链接图标" prop="icon">
            <el-upload
              :class="{ uploadSty: showBtnImg, disUploadSty: noneBtnImg }"
              :ref="imageUpload"
              action="#"
              accept="image/png,image/gif,image/jpg,image/jpeg"
              list-type="picture-card"
              :limit="imageUpload.limitNum"
              :auto-upload="false"
              :before-upload="handleBeforeUpload"
              :on-change="imgChange"
              :on-remove="handleImgRemove"
              :file-list="headImages">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </div>
        <div style="float: left; width: 50%">
          <el-form-item label="链接分类" prop="type">
            <el-select v-model="linkForm.type" placeholder="请选择链接分类">
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.name"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="链接地址" prop="url">
            <el-input v-model="linkForm.url" placeholder="请输入链接地址" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {linkList,selectById,insertLink,updateLink,deleteLink} from "@/api/link";
  export default {
    data() {
      return {
        query: {
          name: '',
          type: '',
          pageNum: 1,
          pageSize: 10,
        },
        linkList: [],
        typeList: [
          {
            name: '前端',
            value: 1
          },
          {
            name: '后端',
            value: 2
          },
          {
            name: '虚拟机',
            value: 3
          },
          {
            name: '镜像',
            value: 4
          },
          {
            name: '其他博客',
            value: 5
          },
          {
            name: '教程',
            value: 6
          },
          {
            name: '工具',
            value: 7
          },
        ],
        loading: true,
        total: 0,
        // 对话框标题
        title: '',
        headImages:[],
        // 是否显示弹出层
        open: false,
        isUploadImg: true,
        showBtnImg: true,
        noneBtnImg: false,
        limitCountImg: 1,
        imageUpload: {
          uploadFiles:[],
          //上传限制
          limitNum: 1, //需要修改为隐藏添加图片的入口
          // 上传的地址
          // url: "http://localhost:9000/static/common/upload", // 上传的图片服务器地址
        },
        // 修改表单参数
        linkForm: {},
        // 添加/修改对话框规则
        linkRules: {
          name: [
            { required: true, message: '请输入链接名称', trigger: 'blur'}
          ],
          url: [
            { required: true, message: '请输入链接地址', trigger: 'blur'},
          ],
          icon: [
            { required: true, message: '请上传链接图标', trigger: 'blur' },
          ],
          type: [
            { required: true, message: '请选择链接类型', trigger: 'blur' },
          ]
        },
      }
    },
    mounted() {
      this.getList()
    },
    watch:{
      open(newValue,oldValue){
        if(!newValue){
          this.headImages.pop();
          this.noneBtnImg=false;
        }
      }
    },
    methods: {
      // 链接列表
      getList(){
        this.loading = true
        linkList(this.query).then( res => {
          this.linkList = res.data.rows
          this.total = res.data.total
          this.loading = false
        })
      },
      // 多选
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 初始页pageNum、初始每页数据数pageSize和数据data
      handleSizeChange: function (size) {
        this.query.pageSize =  size;
        this.getList(); // 数据发生改变重新申请数据
      },
      handleCurrentChange: function(pageNum){
        this.query.pageNum = pageNum;
        this.getList(); // 数据发生改变重新申请数据
      },
      // 图片上传
      handleBeforeUpload(file) {
        if (!(file.type === "image/png" ||
          file.type === "image/gif" ||
          file.type === "image/jpg" ||
          file.type === "image/jpeg")
        ){
          this.$notify.warning({
            title: "警告",
            message: "请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片",
          });
        }
        let size = file.size / 1024 / 1024 / 2;
        if (size > 2) {
          this.$notify.warning({
            title: "警告",
            message: "图片大小必须小于2M",
          });
        }
      },
      imgChange(file, fileList) {
        this.linkForm.icon = file.url
        this.noneBtnImg = fileList.length >= this.limitCountImg;
      },
      handleImgRemove(file, fileList) {
        this.noneBtnImg = fileList.length >= this.limitCountImg;
      },
      // 添加链接
      handleInsert(){
        this.reset()
        this.open = true
        this.title = '添加链接'
      },
      // 修改链接
      handleUpdate(row){
        this.reset()
        selectById(row.id).then( res => {
          this.linkForm = res.data.data
          this.headImages.push({url:this.linkForm.icon})
        })
        this.noneBtnImg=true;
        this.open = true
        this.title = '修改链接'
      },
      // 删除链接
      handleDelete(row){
        this.$confirm('是否确认删除用户', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(function () {
          return deleteLink(row.id)
        }).then(() => {
          this.getList()
          this.$message.success("删除成功！！！")
        }).catch(() => {

        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.linkForm = {
          id: null,
          name: null,
          icon: null,
          url: null,
          type: null,
        };
      },
      // 提交按钮
      submitForm(){
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if(this.linkForm.id != null){
              console.log(this.linkForm);
              updateLink(this.linkForm).then( res => {
                console.log(res);
                if(res.data.code === 200){
                  this.$message.success("修改成功！！")
                  this.open = false
                  this.getList()
                }else {
                  this.$message.error("修改失败！！")
                }
              })
            }else {
              insertLink(this.linkForm).then( res => {
                if(res.data.code === 200){
                  this.$message.success("添加成功！！")
                  this.open = false
                  this.getList()
                }else {
                  this.$message.error("添加成功！！")
                }
              })
            }
          }
        })
      }
    }
  }
</script>

<style>
  .disUploadSty .el-upload--picture-card {
    display: none; /* 上传按钮隐藏 */
  }
</style>
